package com.practice.bootdemo.config;

import com.practice.bootdemo.common.R;
import com.practice.bootdemo.common.MyException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * author :zhoushunquan
 * description: @ControllerAdvice 标志控制器全局的配置都在这里配置,它组合了@Component注解
 * 在这里可使用@ExceptionHandler（统一处理出现的异常）
 *
 * @InitBinder 用来设置WebDataBinder自动绑定前台请求参数到Model中
 * @ModelAttribute 让全局的@RequestMapping都能获取到此处设置的值
 * create date: 2018/5/31 15:14
 * last modify by:v-zhousq04
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 所有地方抛出的异常，此处统一处理，返回统一的错误异常的json
     *
     * @param request
     * @param targetException
     * @return
     */
    @ExceptionHandler({Throwable.class})
    @ResponseBody
    public R systemErr(HttpServletRequest request, Throwable targetException) {
        String msg = "";
        if (targetException instanceof MyException) {
            log.error(targetException.getMessage(), targetException);
            msg = targetException.getMessage();
        } else if (targetException instanceof RuntimeException) {
            log.error(targetException.getMessage(), targetException);
            msg = targetException.getMessage();
        } else {
            msg = "系统异常";
            log.error(targetException.getMessage(), targetException);
        }
        return R.failed(msg);
    }

    /**
     * 让全局的@RequestMapping都能获取到此处设置的值
     * 在任何一个@RequestMapping方法中，接受的参数加入
     * 例如：方法名（@ModelAttribute("attrTest") attrTest ,参数2）
     *
     * @param model
     */
   /* @ModelAttribute
    public void addGlobalAttribute(Model model) {
        model.addAttribute("commonAttr", "globalAttributeTest");
    }*/

    /**
     * 用来设置WebDataBinder自动绑定前台请求参数到Model中
     */
    /*@InitBinder
    public void initBinder(WebDataBinder WebDataBinder) {
        WebDataBinder.setDisallowedFields("id");
    }*/
}
